var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
var map = null;
var toolbar = null;
var scale = null;
var circle = {};
var pointMarker = {};//轨迹点对象
var poly = {};
var style = {
        color:'#FC740F',
        fillColor:'#FC740F',
        fillOpacity:0.2,
        weight:3
    };
var style4 = {
        color:'#D31AAA',
        fillColor:'#D31AAA',
        fillOpacity:0.2,
        weight:3
    };
var style1 = {
        color:'red',
        fillColor:'blue',
        fillOpacity:0.2,
        weight:3
    };
var style2 = {
        color:'blue',
        fillColor:'yellow',
        fillOpacity:0.2,
        weight:3
    };
var style3 = {
        color:'blue',
        fillColor:'red',
        fillOpacity:0.2,
        weight:3
    };
$(function(){
	initPages();
	window.onresize = function () {
		initPages();
	};
	initMap();
	pageBtns();
	pointPantoStudent();
	getSchoolFence();
});
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
}
function getNowCity(){
	  //加载城市查询插件
  AMap.service(["AMap.CitySearch"], function() {
      //实例化城市查询类
      var citysearch = new AMap.CitySearch();
      //自动获取用户IP，返回当前城市
      citysearch.getLocalCity(function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
              if (result && result.city && result.bounds) {
                  var citybounds = result.bounds;
                  //地图显示当前城市
                  map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
              }
          }
      });
  });
}

function pointPantoStudent(){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var studentCode = $(".students-choice-select",parent.document).attr("studentcode");
	var studentname = $(".students-choice-select",parent.document).attr("name");
	var data = {
			cmd:"getPositionByStudentCode",
			model:"position",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
	};
	AjaxCrud.get2(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data;
			var pointArr = data.lonLat.split(",");
			var y = pointArr[0];
			var x = pointArr[1];
			var showObj = {};
			showObj["学生"] = studentname;
			showObj["IMEI"] = data.imei;
			showObj["数据时间"] = data.time;
			showObj["手机"] = data.cellphone;
			if(data.address != null){
				showObj["当前位置"] = data.address;
			}else{
				showObj["当前位置"] = "暂时不能定位到准确地点";
			}
			
			if(pointMarker["dangqian"]){
				pointMarker["dangqian"].setMap(null);
			}
			var imgUrl = "";
			if(data.type == 0 || data.type == "0"){
				imgUrl = '../../../../img/position/lixian.png';
				showObj["定位方式"] = "离线";
			}else if(data.type == 1 || data.type == "1"){
				imgUrl = '../../../../img/position/beidou.png';
				showObj["定位方式"] = "北斗定位";
			}else if(data.type == 2 || data.type == "2"){
				imgUrl = '../../../../img/position/shinei.png';
				showObj["定位方式"] = "蓝牙定位";
				var roomD = JSON.parse(data.remark);
				showObj["室内地图"] = "<a href='javascript:void(0);' onClick=\"enterRoom('"+roomD.scale+"','"+roomD.x+"','"+roomD.y+"','"+roomD.build_name + roomD.floor+"','"+roomD.build_id+"','"+roomD.floor+"','"+showObj["学生"]+"','"+showObj["手机"]+"');\" class='enter-room'>进入</a>";
			}else if(data.type == 3 || data.type == "3"){
				imgUrl = '../../../../img/position/jizhan.png';
				showObj["定位方式"] = "基站定位";
			}
			showObj["终端电量"] = "<img src='../../../../img/position/power_"+ data.power +".png' style='padding-top:5px;'/>";
			var icon = new AMap.Icon({
				size:new AMap.Size(40,40),//图标大小
				image:imgUrl,//大图地址
				imageSize:new AMap.Size(40,40)
			});
			addMarker(x,y,icon,showObj,"dangqian");
			map.panTo(new AMap.LngLat(y,x));
		}else{
			getNowCity();
		}
	},null,null);
}
function enterRoom(scale,x,y,name,buildid,floor,stuname,stuphone){
	$(".index-dialog-cover",top.document).show();
	$(".room-map-dialog",top.document).show();
	var imgUrl = "schoolimg/"+buildid+"-"+floor.toUpperCase()+".jpg";
	new RoomMap.initMap($("#room-map",top.document),scale,imgUrl);
	if(stuphone == undefined || stuphone == "undefined"){
		stuphone = "";
	}
	RoomMap.addPoint(x,y,"img/img.png",{
		title:stuname,
		height:100,
		contents :"<div class='di-le-na'>姓名</div><div class='di-ri-va'>"+stuname+"</div>" +
		"<div class='di-le-na'>当前位置</div><div class='di-ri-va'>"+name.toUpperCase()+"</div>",
	});
}
function getSchoolFence(){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var studentCode = $(".students-choice-select",parent.document).attr("studentcode");
	var data = {
			cmd:"getSchoolFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
			
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		for(var key in circle){
			circle[key].setMap(null);
		}
		circle = {};
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var fencepoint = res.data.center.split(",");
			var x = fencepoint[0] * 1;
			var y = fencepoint[1] * 1;
			var fenceradius = res.data.radius;
			addCircle("schoolfence",new AMap.LngLat(x,y),fenceradius*100,style);
		}else{
			processError("学校围栏加载失败！");
		}
		getStudentFence(userKey,studentCode);
	},null,null);
}
function getStudentFence(userKey,studentCode){
	processBegin("数据加载中···");
	var data = {
			cmd:"getFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		for(var key in circle){
			if(key != "schoolfence"){
				circle[key].setMap(null);
			}
		}
		if(res.result == 1){
			processEnd("数据加载成功");
			var list = res.data;
			for(var i = 0; i < list.length; i++){
				var latlngStr = list[i].fencepoint;
				var listArr = latlngStr.split(",");
				if(list[i].type == 1){
					addCircle("circle"+list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*100,style1);
				}else if(list[i].type == 2){
					addCircle("circle"+list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*100,style2);
				}else if(list[i].type == 2){
					addCircle("circle"+list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*100,style3);
				}
			}
		}else{
			processError("学生围栏加载失败！");
		}
	},null,null);
}

var markers = [];
//添加点方法并注册线点击事件
function addMarker(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
    clickLayer(pointMarker[name],function(){
    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:35%;font-size:15px;'>"+key+"：</td><td style='font-size:15px;'>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
    });
}

function clickLayer(layer,method){
	AMap.event.addListener(layer, "click", method);
}
function addPolygon(name,latlngs,options){
	if(poly[name]){
		poly[name].setMap(null);
	}
	poly[name] = new AMap.Polygon({
		id:name,//多边形ID
		path:latlngs,//多边形顶点经纬度数组
		strokeColor:options.color,//线颜色
		strokeWeight:3,	//线宽
		fillColor: options.fillColor,//填充色
		fillOpacity: 0.2 //填充透明度
	});
	poly[name].setMap(map);
}
function addCircle(name,latlng,radius,options){
	if(circle[name]){
		circle[name].setMap(null);
	}
	circle[name] = new AMap.Circle({
		id:name,
		center:latlng,//圆心，基点
		radius:radius,//半径
		strokeColor: options.color,//线颜色
		strokeOpacity: 1,//线透明度
		strokeWeight: 3,//线宽
		fillColor: options.fillColor,//填充颜色
		fillOpacity: 0.2//填充透明度
	});
	circle[name].setMap(map);
}
function pageBtns(){
	$(".students-choice",parent.document).unbind("click");
	$(".students-choice",parent.document).click(function(){
		$(".students-choice",parent.document).removeClass("students-choice-select");
		$(this).addClass("students-choice-select");
		pointPantoStudent();
		getSchoolFence();
	});
	window.setInterval(pointPantoStudent, 30*1000);
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width();
	$("#map").width(bodyRW);		
	
}